// pages/suborder/suborder.js
var app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    num:0,
    goodsInfo:null,
    skusInfo:null,
    payType:1,
    hasAdr:true,
    orderId:'',//生成订单的订单号
    address:null,
    r:null,
    adrId:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let pid = wx.getStorageSync('buysingleId');//商品id
    let skuId = wx.getStorageSync('buysingleskuId');//商品规格参数组合id
    let n = wx.getStorageSync('buysingleNum');//数量 
    let skuinfo = wx.getStorageSync('buysingleinfo');//商品详情
    console.log(skuinfo)
    console.log("shul" + n)
    this.setData({ num: n, skusInfo:skuinfo})
    let self = this;
    // wx.request({
    //     url: app.globalData.reqPath + 'shop/GoodsProducts/' + pid,
    //     header: {
    //       'authorization': app.globalData.authorization
    //     },
    //     success: function ({ data, header }) {
         
    //       if (data.code == 200) {
    //         let list = data.data.skus;
    //         let info1 = data.data;
    //         console.log(info1)
    //         let info2 = null;
    //         for (let i in list) {
    //           if (list[i].id == skuId) {
    //             info2 = list[i]
    //           }
    //         }
    //         console.log(info2)
    //         self.setData({ goodsInfo: info1, skusInfo: info2, subprice:info2.vipPrice });
    //         self.setData({ orderPrice: self.data.subprice * n })
    //       }
    //     }
    // })
    if(options.r){
      this.setData({ r: options.r})
    }
    if (options.adrId){
      this.setData({ adrId: options.adrId })
    }
    
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let self=this;
    //收货地址
    if (this.data.r == 1) {
      wx.request({
        url: app.globalData.reqPath + 'shop/MembersAddress',
        header: {
          'authorization': app.globalData.authorization
        },
        success: function ({ data, header }) {
          if (header.authorization && header.authorization != app.globalData.authorization) {
            app.globalData.authorization = header.authorization;
          }
          if (data.code == 200) {
            let address = data.data;
            if (address.length == 0) {
              self.setData({ hasAdr: false })
            } else {
              self.setData({ hasAdr: true });
              let defualtaddress = null;
              defualtaddress = address.filter(function (item) {
                return item.isDefault == 1;
              })
              if (defualtaddress.length > 0) {

                self.setData({ address: defualtaddress[0] });

              }
            }


          }
        }
      })
    } else {
      wx.request({
        url: app.globalData.reqPath + 'shop/MembersAddress/' + this.data.adrId,
        header: {
          'authorization': app.globalData.authorization
        },
        success: function ({ data, header }) {
          if (data.code == 200) {
            let address = data.data;
            self.setData({ address: address });
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  goaddressList: function () {
    wx.navigateTo({
      url: "/pages/addressList/addressList?r=1",
    })
  },
  onClickButton: function () {
    let self = this;
    if (!this.data.address) {
      wx.showToast({
        title: '请添加地址',
        icon: 'none'
      })
      return false;
    }
   
    let data = {
        skuAndNum: JSON.stringify([[this.data.skusInfo.id, parseInt(this.data.num)]]),
        addressId: this.data.address.id
      }    
    console.log(JSON.stringify(data))
    if (self.data.payType == 1){//余额支付
        let userInfo = wx.getStorageSync('userInfo');
          if (userInfo.tradePasswordSet == 0) {
              wx.showModal({
                content: '没有支付密码，去设置',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/setpaw/setpaw',
                    })
                  }
                }
              })
            } else {
            wx.showLoading({
              title: '提交中',
              mask:true
            })
            wx.request({//生成订单
                url: app.globalData.reqPath + 'shop/orders',
                data: data,
                header: {
                  'authorization': app.globalData.authorization
                },
                method: 'POST',
                success: function ({ data, header }) {
                  console.log(data)
                  if (data.code == 200) {
                    let id = data.data;
                    wx.hideLoading()
                    self.setData({ orderId: id })
                        self.setData({ show: true })
                      }
                }
              })
    }
    }else{//微信支付
      wx.showLoading({
        title: '提交中',
        mask: true
      })
      wx.request({//生成订单
        url: app.globalData.reqPath + 'shop/orders',
        data: data,
        header: {
          'authorization': app.globalData.authorization
        },
        method: 'POST',
        success: function ({ data, header }) {
          console.log(data)
          if (data.code == 200) {
            let id = data.data;
            self.setData({ orderId: id })
            wx.request({
              url: app.globalData.reqPath + 'shop/OrdersStatusPay',
              method: 'POST',
              header: {
                'authorization': app.globalData.authorization
              },
              data: {
                orderId: id,
                payType: 5,
              },
              success: function ({ data }) {
                console.log(data)
                let wxpaydata = data.data;
                if (data.code == 200) {
                  wx.requestPayment({
                    timeStamp: wxpaydata.timeStamp,
                    nonceStr: wxpaydata.nonceStr,
                    package: wxpaydata.package,
                    signType: wxpaydata.signType,
                    paySign: wxpaydata.paySign,
                    success(res) {
                      console.log(res)
                      if (res.errMsg == "requestPayment:ok") {
                        wx.redirectTo({
                          url: '/pages/order/order?s=2',
                        })
                      }
                    },
                    fail(res) {
                      if (res.errMsg == 'requestPayment:fail cancel') {//res.errMsg //requestPayment: fail cancel //用户取消支付
                        wx.redirectTo({
                          url: '/pages/order/order?s=1',
                        })
                      } else { //requestPayment: fail(detail message)//调用支付失败
                        wx.showToast({
                          title: '支付失败，请重试',
                          icon: 'none'
                        })
                      }
                    }
                  })
                }
              }
            })  
          }
        }
      })     
    }
  },
  comfirmpawPay:function(e){//输入密码点确认
    let paw = e.detail.value.paw;
    let self = this;
    wx.request({
      url: app.globalData.reqPath + 'shop/OrdersStatusPay',
      data: {
        orderId: this.data.orderId,
        payType: 1,
        tradePassword: paw
      },
      header: {
        'authorization': app.globalData.authorization
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '支付成功',
          })
          setTimeout(function(){
            wx.redirectTo({
              url: '/pages/order/order?s=2',
            })
          },300)
        
        } else {
          wx.showToast({
            title: res.data.data.msg,
            icon: 'none',
            success: function () {
              self.setData({ show: false })
            }
          })
        }
      }
    })
  },
  changePayway:function(e){
    this.setData({ payType: e.detail.value })
  },
  onClose:function(){
    this.setData({ show: false })
  }
})